// 短信发送倒计时
var msnLeftTime = 0;
var expire_time;
// 微信登录刷新次数,5分钟
var mpCheckTimes = 100;
// 公众号是否登录
var mpCheckd = 1;
var mpRefreshTime = 3000;
var timestamp = Math.round(new Date().getTime() / 1000);
var platfrom, login_style, register_style, checktoken,checktime,checksign,unionid;
var device = "pc";
var _throttle = true;
var isIE = false;


$(document).ready(function() {
    platfrom = $("#platfrom").val();
    login_style = $("#login_style").val();
    register_style = $("#register_style").val();
    // 获取用户代理字符串
    var userAgent = window.navigator.userAgent;

    // 判断是否为 IE 浏览器
    isIE = userAgent.indexOf("MSIE") !== -1 || userAgent.indexOf("Trident/") !== -1;

    if (isIE) {
        $(".login-cotainer-right").remove();
        $(".login-cotainer-left").css({borderRight:'none',width:'100%'});
        $(".login-cotainer-content").css({justifyContent:'center'});
        $("#wechat_title").text('本系统不支持IE浏览器，建议使用其他浏览器操作或使用小程序操作。');
        $("#wechat_title").css({color:'red',backgroundColor:'rgba(255,0,0,.1)'});
        $("#wechat_describe").text('打开微信扫一扫,快速体验小程序。');
        $(".qrcode-img").css("background-image", "url('https://res.wailian1.cn/miniapp/links/20230712/6fbe7d1340011f3e51d3a705cc6154c2.jpg')");
        if (!localStorage.getItem("upie")){
            uploadIe();
        }
       return false;
    } 
    getcode();
    // 判断是手机还是电脑
    isMobile();

    msnLeftTime = localStorage.getItem("msnLeftTime") || 0;
    if (msnLeftTime >= 0) {
        countDown();
    }

    // 判断页面是否返回，如果返回后则刷新页面
    var isPageHide = false;
    window.addEventListener('pageshow', function() {
        if (isPageHide) {
            window.location.reload();
        }
    });
    window.addEventListener('pagehide', function() {
        isPageHide = true;
    });

    if ($(window).width() < 730) {
        $(".login-cotainer-left").hide();
        $("#login_cotainer").css({ "width": "90%", "margin": "3rem 5%" });
    }

    $(window).resize(function() {
        if ($(window).width() < 730) {
            $(".login-cotainer-left").hide();
            $("#login_cotainer").css({ "width": "90%", "margin": "3rem 5%" });
        } else {
            $(".login-cotainer-left").show();
            $("#login_cotainer").css({ "width": "730px", "margin": "3rem auto" });
        }
    });

    $(".login-type li").click(function() {
        $(".login-type li").removeClass("active");
        $(this).addClass("active");
        var id = $(this).attr("id");
        if (id == "type_phone") {
            $("#login_from_phone").show();
            $("#login_from_username").hide();
            $("#login_type").val("phone");
            $("#loginbtn").text("登录/注册");
        } else {
            $("#login_from_phone").hide();
            $("#login_from_username").show();
            $("#login_type").val("password");
            $("#loginbtn").text("登录");
        }
    });
});

function getcode() {
    //判断上一个页面携带的参数
    let previous = $("#previous").val().split("?")[1] || '';
    // 利用正则表达式
    let url = window.location.href.split("?")[1] || '';
    if(previous && previous.length>0 && queryURLParams(previous).keyword && queryURLParams(previous).keyword.length > 0){
        localStorage.setItem('keyword',queryURLParams(previous).keyword);
    }else{
        if(url && url.length>0 && queryURLParams(url).keyword && queryURLParams(url).keyword.length > 0){
            localStorage.setItem('keyword',queryURLParams(url).keyword);
        }
    }
    if(previous && previous.length>0 && queryURLParams(previous).code && queryURLParams(previous).code.length > 0){
        localStorage.setItem('code',queryURLParams(previous).code);
    }else{
        if(url && url.length>0 && queryURLParams(url).code && queryURLParams(url).code.length > 0){
            localStorage.setItem('code',queryURLParams(url).code);
        }
    }
    if(previous && previous.length>0 && queryURLParams(previous).ncode && queryURLParams(previous).ncode.length > 0){
        localStorage.setItem('ncode',queryURLParams(previous).ncode);
    }else{
        if(url && url.length>0 && queryURLParams(url).ncode && queryURLParams(url).ncode.length > 0){
            localStorage.setItem('ncode',queryURLParams(url).ncode);
        }
    }
}

function queryURLParams(url) {
    if(url){
        let obj = {}; // 声明参数对象
        let arr = url.split("&"); // 以&符号分割为数组
        for (let i = 0; i < arr.length; i++) {
            let arrNew = arr[i].split("="); // 以"="分割为数组
            obj[arrNew[0]] = arrNew[1];
        }
        return obj; 
    }else{
        return false; 
    }  
}

function isMobile() {
    var userAgentInfo = navigator.userAgent;
    var mobileAgents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
    var mobile_flag = false;
    //根据userAgent判断是否是手机
    for (var v = 0; v < mobileAgents.length; v++) {
        if (userAgentInfo.indexOf(mobileAgents[v]) > 0) {
            mobile_flag = true;
            break;
        }
    }
    if (mobile_flag) {
        device = "phone";
        $("#qrcode_notice").css("opacity", "100");
        $("#qrcode_notice p").text("获取二维码");
        mpLogin();
        return mobile_flag;
    }

    var screen_width = window.screen.width;
    var screen_height = window.screen.height;

    //根据屏幕分辨率判断是否是手机
    if (screen_width < 500 && screen_height < 800) {
        mobile_flag = true;
    }
    if (mobile_flag) {
        device = "phone";
        $("#qrcode_notice").css("opacity", "100");
        $("#qrcode_notice p").text("获取二维码");
        mpLogin();
    } else {
        // 登录类型支持微信登录,展示登录二维码
        if (login_style == "mp" || login_style == "mpp") {
            getOffiaccountQrcode();
        }
    }
    return mobile_flag;
}

function mpLogin() {
    var wechat = isWeChat();
    if (wechat) {
        var unionid = $("#unionid").val();
        if (unionid == "") {
            window.location.href = "/admin/mp_login";
        } else {
            mpBindPhone(unionid);
        }
    }
}

function countDown() {
    msnLeftTime = msnLeftTime - 1;
    $("#shortCode").text(msnLeftTime + "秒后重新获取").addClass("active").attr("onclick", "");;
    if (msnLeftTime <= 0) {
        $("#shortCode").text("获取短信验证码").removeClass("active").attr("onclick", "getShortMessageCode();");
        msnLeftTime = 60;
        return;
    }
    // 记录开始倒计时
    localStorage.setItem("msnLeftTime", msnLeftTime);
    setTimeout("countDown()", 1000);
}

function countExpireTimeDown() {
    var nowtimestamp = Math.round(new Date().getTime() / 1000);
    var runTime = (expire_time - nowtimestamp) - 2;
    if (runTime > 60) {
        var minute = Math.floor(runTime / 60)
        var second = runTime % 60;
        var leftTime = minute + "分" + second + "秒";
    } else {
        var leftTime = runTime + "秒";
    }
    if (mpCheckd == 2) return;
    if (mpCheckd == 3) {
        $("#qrcode_describe").text("关注成功,首次注册请绑定手机号!");
        return;
    }
    $("#qrcode_describe").text("二维码" + leftTime + "后过期");
    if (runTime <= 0) {
        $(".qrcode-img").css("background-image", "url()");
        $("#qrcode_describe").text("二维码已过期");
        $("#qrcode_notice").css("opacity", "100");
        return;
    }
    setTimeout("countExpireTimeDown()", 1000);
}

function inputChange(id) {
    setTimeout(()=>{
        var value = $("#" + id).val();
        if (id == "phone") {
            var isphone = isPhoneNo(value);
            if (!isphone) {
                $("#notice_phone").show().text("请输入正确的手机号码!");
            } else {
                $("#notice_phone").hide();
            }
        } else if (id == "captcha") {
            if (value == "" || value.length < 4) {
                $("#notice_captcha").show().text("请输入正确的图形验证码!");
            } else {
                $("#notice_captcha").hide();
            }
        } else if (id == "msncode") {
            if (value == "" || value.length < 4) {
                $("#notice_msncode").show().text("请输入正确的短信验证码!").removeClass("text-success");
            } else {
                $("#notice_msncode").hide();
            }
        } else if (id == "username") {
            var isphone = isPhoneNo(value);
            if (!isphone) {
                $("#notice_username").show().text("请输入正确的登录账号!");
            } else {
                $("#notice_username").hide();
            }
        } else if (id == "password") {
            if (value == "" || value.length <= 4) {
                $("#notice_password").show().text("请输入正确的登录密码!");
            } else {
                $("#notice_password").hide();
            }
            var ischina = isChinaName(value);
            if (ischina) {
                $("#notice_password").show().text("登录密码不能包含中文!");
            } else {
                $("#notice_password").hide();
            }
        } else if (id == "agreement") {
            var agreement = $("#agreement").is(":checked");
            if (agreement) {
                $("#loginbtn").removeClass("button-disable");
            } else {
                $("#loginbtn").addClass("button-disable");
            }
        }
    },100)
}

function captchaChange() {
    $("#captchaImg").attr("src", '/admin/captcha_image?' + Math.random());
}

function isPhoneNo(phone) {
    var pattern = /^1[3456789]\d{9}$/;
    return pattern.test(phone);
}

function isNumber(nubmer) {
    var pattern = /^[0-9]+.?[0-9]*$/;
    return pattern.test(nubmer);
}

function isChinaName(name) {
    var pattern = /.*[\u4e00-\u9fa5]+.*$/;
    return pattern.test(name);
}

function isWeChat() {
  var ua = navigator.userAgent.toLowerCase();
  return ua.indexOf("micromessenger") !== -1;
}

function getShortMessageCode() {
    var phone = $("#phone").val();
    var captcha = $("#captcha").val();
    var need_captcha = $("#need_captcha").val();
    var isphone = isPhoneNo(phone);
    if (!isphone) {
        $("#notice_phone").show().text("请输入正确的手机号码!");
        return false;
    }
    if (need_captcha == 2) {
        var iscaptcha = isNumber(captcha);
        if (captcha == "") {
            $("#notice_msncode").show().text("请输入图形验证码!").removeClass("text-success");
            return false;
        }
        if (!iscaptcha) {
            $("#notice_msncode").show().text("请输入正确的图形验证码!").removeClass("text-success");
            return false;
        }
    }
    var nowtimestamp = Math.round(new Date().getTime() / 1000);
    //短信发送  
    $.ajax({
        "url": "/api/version/1/send_msn",
        "type": "GET",
        data: {
            "unionid": unionid,
            "time": $("#ms_time").val(),
            "sign": $("#ms_sign").val(),
            "phone": phone,
            "captcha": captcha,
        },
        success: function(res){
            if (res.status == "success") {
                $("#need_captcha").val(res.need_captcha);
                if (res.need_captcha == 2) {
                    captchaChange();
                    $("#captcha_row").show();
                } else {
                    $("#captcha_row").hide();
                }
                // 短信验证码倒计时
                msnLeftTime = 60;
                countDown();
                $("#notice_msncode").show().text(res.msg).addClass("text-success");
            } else {
                $("#notice_msncode").show().text(res.msg).removeClass("text-success");
            }
        },
        error: function(err){
            $("#notice_msncode").show().text("发送失败,请稍后重试或联系客服反馈!").removeClass("text-success");
        }
    });
}

function getOffiaccountQrcode() {
    if(isIE) return false;
    $("#qrcode_notice").css("opacity", "0");
    token = CryptoJS.MD5(platfrom + "S" + timestamp + "A").toString();
    $.ajax({
        type: 'GET',
        url: "https://bab.moreqifu.cn/api/offiaccount/get_qrcode",
        data: {
            "platfrom": platfrom,
            "timestamp": timestamp,
            "token": token,
        },
        success: (res) => {
            if (res.status == "success") {
                $(".qrcode-img").css("background-image", "url(" + res.data.qrcodeurl + ")");
                checktoken = res.data.token;
                checktime = res.data.time;
                checksign = res.data.sign;
                // 更新二维码过期时间
                expire_time = res.data.time + 300;
                // 初始化刷新次数
                mpCheckTimes = 100;
                // 加载二维码过期时间
                countExpireTimeDown();
                // 定时查询公众号登录情况
                checkQrcodeTimeDown();
            } else {
                $("#qrcode_notice").css("opacity", "100");
                $("#qrcode_notice p").text("重新获取二维码");
                $("#qrcode_describe").text(res.msg);
            }
        },
        error: () => {
            $(".login-cotainer-left").hide();
            $("#login_cotainer").attr("class", "login-cotainer-small");
            device = "phone";
        }
    });
}

function checkQrcodeTimeDown() {
    mpCheckTimes = mpCheckTimes - 1;
    if (mpCheckd == 2) {
        $("#qrcode_describe").text("公众号登录成功");
        return;
    }
    if (mpCheckTimes <= 0) {
        return;
    }
    if (mpCheckTimes >= 90) {
        mpRefreshTime = 3000;
    }
    // 2分钟后,每次刷新加一1秒
    if (mpCheckTimes <= 60) {
        mpRefreshTime += 1000;
    }
    // 记录开始倒计时
    setTimeout("checkOffiaccountQrcode()", mpRefreshTime);
}

function checkOffiaccountQrcode() {
    var token = checktoken;
    var time = checktime;
    var sign = checksign;
    var code = localStorage.getItem('code') ? localStorage.getItem('code') : "";
    var keyword = localStorage.getItem('keyword') ? localStorage.getItem('keyword') : "";
    var ncode = localStorage.getItem('ncode') ? localStorage.getItem('ncode') : "";
    var returnurl = $("#returnurl").val();
    var username = $("#checked_phone").val();
    if(device == 'pc'){
        device = 1;
    }else if(device == 'phone'){
        device = isWeChat() ? 4 : 2;
    }
    $.ajax({
        type: 'GET',
        url: "/admin/login_check",
        data: {
            "token": token,
            "time": time,
            "sign": sign,
            "code": code,
            "keyword": keyword,
            "ncode": ncode,
            "username": username,
            "device":device
        },
        success: function(res) {
            if (res.status == "success") {
                $("#qrcodenotice").html("登录成功,正在跳转...");
                if (res.username == "") {
                    mpCheckd = 3;
                    $(".login-cotainer-left").hide();
                    $("#login_cotainer").attr("class", "login-cotainer-small");
                    $(".login-type").hide();
                    $("#loginbtn").text("立即绑定手机号");
                    $("#phone_bind").show();
                    unionid = res.unionid;
                } else {
                    mpCheckd = 2;
                    try {
                        window.location.href = res.jump;
                    } catch(e) {
                        window.location.href = '/admin/links_lists/lists';
                    }
                }
            }else{
                checkQrcodeTimeDown();
            }
        },
        error: function(XMLHttpRequest, textStatus) {
            checkQrcodeTimeDown();
        }
    });
}

function mpBindPhone(mpUnionid) {
    mpCheckd = 3;
    $(".login-cotainer-left").hide();
    $("#login_cotainer").attr("class", "login-cotainer-small");
    $(".login-type").hide();
    $("#loginbtn").text("立即绑定手机号");
    $("#phone_bind").show();
    unionid = mpUnionid;
}

function showPassword() {
    var type = $("#password").attr("type");
    if (type == "password") {
        $("#password").attr("type", "text");
        $("#password_hanndle").removeClass("icon-xianshikejian").addClass("icon-yincangbukejian");
    } else {
        $("#password").attr("type", "password");
        $("#password_hanndle").removeClass("icon-yincangbukejian").addClass("icon-xianshikejian");
    }
}

function showServiceQrcode() {
    $('#serviceModal').modal('toggle');
}

function submitFrom() {
    $(".login-error-notice").hide();
    var agreement = $("#agreement").is(":checked");
    if (!agreement) {
        $(".login-error-notice").show().text("请勾选同意协议后再点击登录/注册!");
        return;
    }
    var login_type = $("#login_type").val();
    var phone = $("#phone").val();
    var msncode = $("#msncode").val();
    var username = $("#username").val();
    var password = $("#password").val();
    var openid = $("#openid").val();
    var nowtimestamp = Math.round(new Date().getTime() / 1000);
    var token = CryptoJS.MD5(username + "S" + phone + "A" + nowtimestamp).toString();
    var code = localStorage.getItem('code') ? localStorage.getItem('code') : "";
    var keyword = localStorage.getItem('keyword') ? localStorage.getItem('keyword') : "";
    var ncode = localStorage.getItem('ncode') ? localStorage.getItem('ncode') : "";
    if(device == 'pc'){
        device = 1;
    }else if(device == 'phone'){
        device = isWeChat() ? 4 : 2;
    }
    if(_throttle){
        _throttle = !_throttle
    }else{
        return;
    }
    $.ajax({
        type: "GET",
        url: "/admin/submit_login",
        data: {
            "login_type": login_type,
            "timestamp": nowtimestamp,
            "phone": phone,
            "msncode": msncode,
            "username": username,
            "password": password,
            "unionid": unionid,
            "token": token,
            "device": device,
            "code": code,
            "keyword": keyword,
            "ncode": ncode,
        },
        success: (res) => {
            if (res.status == "success") {
                $("#checked_phone").val(phone);
                // 首次需要绑定公众号
                if (res.code == 2000) {
                    mpCheckd = 1;
                    $(".login-cotainer-left").show();
                    $(".login-cotainer-right").hide();
                    $("#login_cotainer").attr("class", "login-cotainer-small");
                    $(".login-cotainer-left").addClass("login-cotainer-left-full");
                    $("#wechat_bind").show();
                    $("#wechat_title").hide();
                    $("#wechat_describe").hide();
                    // 重新获取公众号二维码
                    getOffiaccountQrcode();
                } else {
                    try {
                        window.location.href = res.data.jump;
                    } catch(e) {
                        window.location.href = '/admin/links_lists/lists';
                    }
                }
            } else {
                $(".login-error-notice").show().text(res.msg);
            }
            setTimeout(()=>{
                _throttle = !_throttle;
            },500)
        },
        error: () => {
            $(".login-error-notice").show().text("网络异常,请稍后尝试!");
            setTimeout(()=>{
                _throttle = !_throttle;
            },1000)
        }
    });
}

function uploadIe(){
    $.ajax({
        type: 'GET',
        url: "/admin/upload_ie",
        success: (res) => {
            if (res.status == "success") {
                localStorage.setItem("upie", 1);
            } 
        },
        error: () => {
            
        }
    });
}
